package com.ywd.platform.websocket.test;

import org.springframework.web.socket.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport;

import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

/**
 * SockJS客户端（兼容Spring的SockJS服务）
 */
public class SockJSClient {

    public static void main(String[] args) {
        // 1. 创建SockJS客户端
        SockJsClient sockJsClient = new SockJsClient(
                Arrays.asList(
                        new WebSocketTransport(new StandardWebSocketClient()),
                        new RestTemplateXhrTransport()
                )
        );

        // 2. 定义WebSocket处理器
        WebSocketHandler handler = new WebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession session) throws Exception {
                System.out.println("[SockJS] 连接成功，会话ID: " + session.getId());
                session.sendMessage(new TextMessage("Hello from client"));
            }

            @Override
            public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
                System.out.println("[SockJS] 收到消息: " + message.getPayload());

            }
            @Override
            public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
                System.err.println("[SockJS] 错误: " + exception.getMessage());
            }

            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
                System.out.println("[SockJS] 连接关闭: " + closeStatus.getReason());
            }

            @Override
            public boolean supportsPartialMessages() {
                return false;
            }
        };

        // 3. 连接服务端（注意协议为http/https）
        sockJsClient.doHandshake(handler, "http://localhost:13000/ws");

        // 4. 保持主线程运行
        new Scanner(System.in).nextLine(); // 按回车键退出
    }
}
